package com.heima.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-14
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {

        if (dto == null || (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {

            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();

            query.eq(ApUser::getPhone, dto.getPhone());

            ApUser one = this.getOne(query);

            if (one == null) {

                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            String salt = one.getSalt();

            String pwdStr = dto.getPassword() + salt;

            String md5Str = DigestUtils.md5DigestAsHex(pwdStr.getBytes());

            if (!md5Str.equals(one.getPassword())) {

                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            Map<String, Object> map = new HashMap<>();

            map.put("userId", one.getId());

            map.put("userName", one.getName());

            String token = AppJwtUtil.getToken(map);

            Map<String, Object> map1 = new HashMap<>();

            one.setPassword(null);

            one.setPhone(null);

            one.setSalt(null);

            map1.put("user", one);

            map1.put("token", token);

            return ResponseResult.okResult(map1);
        }
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {

            Map<String, Object> claimMap = new HashMap<>();

            claimMap.put("userId", 0);

            String token = AppJwtUtil.getToken(claimMap);

            Map<String, Object> map = new HashMap<>();

            map.put("token", token);

            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService followService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //  System.out.println(com.heima.search.dto.getAuthorId());

        User user = AppThreadLocalUtil.get();

        if (user.getUserId() == 0) {

            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApUserFollow userFollow = new ApUserFollow();

        userFollow.setUserId(user.getUserId());

        userFollow.setUserName(user.getUserName());

        //     System.out.println("到底哪里出错了呢");

        ResponseResult<ApAuthor> responseResult = articleFeign.getAuthorById(dto.getAuthorId());

        //  System.out.println("文章作者信息是："+responseResult.getData());

        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = responseResult.getData();
            userFollow.setFollowId(apAuthor.getUserId());
            userFollow.setFollowName(apAuthor.getName());
        }
        userFollow.setLevel(1);

        userFollow.setCreatedTime(new Date());

        LambdaQueryWrapper<ApUserFollow> update = new LambdaQueryWrapper<>();

        LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();

        query.eq(ApUserFollow::getUserId, userFollow.getUserId());

        query.eq(ApUserFollow::getFollowId, userFollow.getFollowId());

        if (dto.getOperation() == 0) {
            // 关注
            ApUserFollow one = followService.getOne(query);
            // 保存
            if (one == null) {
                followService.save(userFollow);
            }
        } else {
            followService.remove(query);
        }
        FollowBehaviorDto behaviorDto = new FollowBehaviorDto();

        behaviorDto.setUserId(userFollow.getUserId());

        behaviorDto.setFollowId(userFollow.getFollowId());

        behaviorDto.setOperation(dto.getOperation());

        behaviorDto.setEquipmentId(dto.getEquipmentId());

        String json = JSON.toJSONString(behaviorDto);

        kafkaTemplate.send(followBehaviorTopic, json);

        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
}
